package wcg;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;

import javax.swing.text.html.HTMLDocument.Iterator;


public class ChannelConfig {
	
	private TreeMap<Integer,ChannelDataDisplayProperty> data;
	private long 	LoadFilelastModified  =0;
	private String ConfFile=null;
	
//	ChannelConfig(){
//		ConfFile = null;
//		data = new TreeMap<Integer,ChannelDataDisplayProperty>();
//	}
	public ChannelConfig(String file){
		ConfFile = new String(file);
		data = new TreeMap<Integer,ChannelDataDisplayProperty>();
	}
	public Set<Integer> getChannelKeySet(){
		return data.keySet();
	}
	public void setData(int ch,ChannelDataDisplayProperty pro){
		ChannelDataDisplayProperty p = data.get(ch);
		if(p == null) p = new ChannelDataDisplayProperty(ch);
		p.hide = pro.hide;
		p.unitType = pro.unitType;
		p.unitFactor = pro.unitFactor;
		p.unitString = pro.unitString;
		p.FullScale = pro.FullScale;
		p.setStation(pro.getStation());
		p.setComponent(pro.getComponent());
		p.setChannelTableIndex(pro.getChannelTableIndex());
		p.Mask = pro.Mask;
		p.Latitude = pro.Latitude;
		p.Longitude = pro.Longitude;
		p.Altitude = pro.Altitude;
		data.put(ch,p);
	}
	public ChannelDataDisplayProperty getData(int ch){
	//	int num = data.size();
		return data.get(ch);
	}
	public void load(){
		if(ConfFile==null) return;
		if(ConfFile.isEmpty()) return;
		load(ConfFile);
	}
	/**
	 * ファイルから読み込む
	 * @param file
	 */
	public void load(String file){
		File tmp = new File(file);
		long last = tmp.lastModified();
		if(LoadFilelastModified == last) return;
		ConfFile = new String(file);
		data.clear();// クリアする
		try{
			BufferedReader br = new BufferedReader(new FileReader(tmp));
			String line = "";
			while((line = br.readLine()) != null){
				int nm = line.indexOf(';');
				if(nm > 0) line = line.substring(0,nm);
				
				StringTokenizer st = new StringTokenizer(line,",");
				String [] tok = new String[st.countTokens()];
				for(int i=0;st.hasMoreTokens();i++){
					tok[i] = st.nextToken().trim();
				}
				if(tok.length>=5){
					int ch=0;
					int hide=0;
					int pu =ChannelDataDisplayProperty.UNIT_TYPE_DIGIT;
					double factor=0.0;
					long fullscale=8388608;
					try{
						ch = Integer.parseInt(tok[0],16);
						if(tok[1].compareToIgnoreCase("y")==0){
							hide = 1;
						}
						if(tok[2].compareToIgnoreCase("y")==0){
							pu = ChannelDataDisplayProperty.UNIT_TYPE_CONV;
						}
						factor = Double.parseDouble(tok[3]);
						if(tok.length>=6) fullscale = Long.parseLong(tok[5]);
						ChannelDataDisplayProperty pro = getData(ch);
						if(pro==null) pro = new ChannelDataDisplayProperty(ch);
						pro.hide = hide;
						pro.unitType = pu;
						pro.unitFactor = factor;
						pro.unitString = tok[4];
						pro.FullScale = fullscale;
						if(tok.length>6) pro.setStation(tok[6]);
						if(tok.length>7) 	pro.setComponent(tok[7]);
						if(tok.length>8) 	pro.setChannelTableIndex(Integer.valueOf(tok[8]));
						if(tok.length>9) 	{
							if(tok[9].equals("n")) pro.Mask=false;
							else pro.Mask=true;
						}
						if(tok.length>10) 	{
							pro.Latitude = Double.parseDouble(tok[10]);
						}
						if(tok.length>11) 	{
							pro.Longitude = Double.parseDouble(tok[11]);
						}
						if(tok.length>12) 	{
							pro.Altitude = Double.parseDouble(tok[12]);
						}
						setData(ch,pro);
					} catch(NumberFormatException e){
						e.printStackTrace();
					}
					
				}
			}
			br.close();
			LoadFilelastModified=last;
			ConfFile = new String(file);
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
	public void save(){
		if(ConfFile.isEmpty() || ConfFile==null) return;
		save(ConfFile);
	}
	public void save(String file){
		try{
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(file)));
			String line = "";
			
			Set<Integer> keyset = data.keySet();
			java.util.Iterator<Integer> ite = keyset.iterator();
			while(ite.hasNext()){
				int ch = ite.next();
				ChannelDataDisplayProperty pro = data.get(ch);
				String ishide = "n";
				String ispu = "n";
				if(pro.hide != 0) ishide = "y";
				if(pro.unitType == ChannelDataDisplayProperty.UNIT_TYPE_CONV) ispu = "y";
				String isMask="n";
				if(pro.Mask)  isMask="y";
				line = String.format("%04x , %s , %s , %g , %s , %d , %s ,%s , %d , %s , %f , %f , %f" , 
						ch,ishide,ispu,pro.unitFactor,pro.unitString,pro.FullScale,
						pro.getStation(),pro.getComponent(),pro.getChannelTableIndex(),isMask,
						pro.Latitude,pro.Longitude,pro.Altitude);
				bw.write(line);
				bw.newLine();
			}
			bw.flush();
			bw.close();
			ConfFile = new String(file);
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		} 
		
	}
	public void save(String file,DialogChannelDisplayProperty dlg){
		try{
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(file)));
			String line = "";
			
			
			int[] cha = dlg.getChannel();
			for(int i=0;i<cha.length;i++){
				int ch = cha[i];
				String ishide = "n";
				String ispu = "n";
				if(!dlg.isDisplay(i)) ishide = "y";
				if(dlg.isPU(i)) ispu = "y";
				String isMask="n";
				if(dlg.getMask(i))  isMask="y";
				line = String.format("%04x , %s , %s , %g , %s , %d , %s ,%s , %d , %s , %f , %f , %f" , 
						ch,ishide,ispu,dlg.getFactor(i),dlg.getUnit(i),dlg.getFullScale(i),
						dlg.getStation(i),dlg.getChComponent(i),dlg.getChannelTableIndex(i),isMask,
						dlg.getLatitude(i),dlg.getLongitude(i),dlg.getAltitude(i));
				//System.out.println(line);
				bw.write(line);
				bw.newLine();
				
			}
			bw.flush();
			bw.close();
			ConfFile = new String(file);
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
	
}
